package com.qdsgjsfk.vision.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.exception.BleException;
import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.base.BaseFragment;
import com.qdsgjsfk.vision.eventbus.BlueTooth;
import com.qdsgjsfk.vision.eventbus.Clear;
import com.qdsgjsfk.vision.eventbus.StartVision;
import com.qdsgjsfk.vision.model.BlueToothDataJson;
import com.qdsgjsfk.vision.service.SocketService;
import com.qdsgjsfk.vision.ui.DeviceTypeActivity;
import com.qdsgjsfk.vision.ui.StudentDetailActivity;
import com.qdsgjsfk.vision.ui.StudentDetailOtherActivity;
import com.qdsgjsfk.vision.ui.dialog.QualifiedDialog;
import com.qdsgjsfk.vision.ui.dialog.RemarkDialog;
import com.qdsgjsfk.vision.util.BleBlueToothUtils;
import com.qdsgjsfk.vision.util.Constant;
import com.qdsgjsfk.vision.util.DiopterDataUtil;
import com.qdsgjsfk.vision.util.FastBleLibUtil;
import com.qdsgjsfk.vision.util.NetUtil;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.qdsgjsfk.vision.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.QualifiedResponse;
import com.rest.response.StudentInfoResponse;
import com.rest.util.HttpDigestUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import util.PreferencesHelper;
import util.UtilList;

/**
 * Created by HP on 2018/10/7.
 */

public class DiopterFragment extends BaseFragment {
    @BindView(R.id.tv_odR1mm)
    TextView tvOdR1mm;
    @BindView(R.id.tv_osR1mm)
    TextView tvOsR1mm;
    @BindView(R.id.tv_odR1d)
    TextView tvOdR1d;
    @BindView(R.id.tv_osR1d)
    TextView tvOsR1d;
    @BindView(R.id.tv_odR2mm)
    TextView tvOdR2mm;
    @BindView(R.id.tv_osR2mm)
    TextView tvOsR2mm;
    @BindView(R.id.tv_odR2d)
    TextView tvOdR2d;
    @BindView(R.id.tv_osR2d)
    TextView tvOsR2d;
    @BindView(R.id.tv_odAX)
    TextView tvOdAX;
    @BindView(R.id.tv_osAX)
    TextView tvOsAX;
    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.btn_remark)
    LinearLayout btnRemark;
    @BindView(R.id.tv_vision)
    TextView tvVision;
    Unbinder unbinder;
    @BindView(R.id.od_Axial)
    TextView tvOdAxial;
    @BindView(R.id.os_Axial)
    TextView tvoSAxial;
    @BindView(R.id.odSph)
    EditText odSph;
    @BindView(R.id.odCyl)
    EditText odCyl;
    @BindView(R.id.osSph)
    EditText osSph;
    @BindView(R.id.osCyl)
    EditText osCyl;
    @BindView(R.id.btn_confirm)
    TextView btn_confirm;
    @BindView(R.id.stuName)
    TextView stuName;
    @BindView(R.id.tv_remark)
    TextView tv_remark;
    @BindView(R.id.tv_examiner)
    TextView tv_examiner;
    @BindView(R.id.odAxial)
    EditText odAxial;
    @BindView(R.id.osAxial)
    EditText osAxial;
    @BindView(R.id.odR1mm)
    EditText odR1mm;
    @BindView(R.id.osR1mm)
    EditText osR1mm;
    @BindView(R.id.odR1d)
    EditText odR1d;
    @BindView(R.id.osR1d)
    EditText osR1d;
    @BindView(R.id.odR2mm)
    EditText odR2mm;
    @BindView(R.id.osR2mm)
    EditText osR2mm;
    @BindView(R.id.odR2d)
    EditText odR2d;
    @BindView(R.id.osR2d)
    EditText osR2d;
    @BindView(R.id.odAX)
    EditText odAX;
    @BindView(R.id.osAX)
    EditText osAX;
    @BindView(R.id.tv_examiner_time)
    TextView tvExaminerTime;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_ble_test)
    TextView tvBleTest;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private InputStream mmInStream;
    private OutputStream mmOutStream;
    String studentId, taskId, taskType, s = "", strName = null, strAddress = null, manual = "0";
    TextView currentView;
    private QualifiedDialog mQualifiedDialog;
    private RemarkDialog mRemarkDialog;
    ProgressDialog progressDialog;
    OptionsPickerView pvOptions_zhujing, pvOptions_qiujing;
    List<String> options1Items = new ArrayList<>();
    List<String> options3Items = new ArrayList<String>();

    List<String> options2Items = new ArrayList<>();
    byte[] testByte = new byte[0];
    private boolean isCanSave = false;
    Activity activity;
    private boolean isEmptyRemark = true;
    private String right_r2_ax, right_avg_mm, right_avg_d, right_kc, left_r2_ax, left_avg_mm, left_avg_d, left_kc, pd, ep_model;
    private String brand, software_version, Id, studentName, stuSex, stuBirth;

    private int bleCount = 0;

    /**
     * EventBus传值
     *
     * @time 2020/5/28 16:00
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(BlueTooth event) {

        if (event.type == 110 || event.type == Constant.BLUE_WSRMK8000) {
            Log.e( "onMessageEvent11======", event.output );
//            Toast.makeText( activity, event.output, Toast.LENGTH_SHORT ).show();
            try {
                if (BaseApplication.strName.contains( "VisionScreener" )) {
                    //美沃数据返回
                    osSph.setText( BlueToothDataJson.showReceiveDataDSOS( event.output ) );
                    osCyl.setText( BlueToothDataJson.showReceiveDataDCOS( event.output ) );
                    osAxial.setText( BlueToothDataJson.showReceiveDataAxisOS( event.output ) );
                    odSph.setText( BlueToothDataJson.showReceiveDataDSOD( event.output ) );
                    odCyl.setText( BlueToothDataJson.showReceiveDataDCOD( event.output ) );
                    odAxial.setText( BlueToothDataJson.showReceiveDataAxisOD( event.output ) );
                } else {
//                    tvBleTest.setText( event.output );
                    JSONObject object = new JSONObject( event.output );
                    String right_s_avg = object.optString( "right_s_avg" );
                    String right_c_avg = object.optString( "right_c_avg" );
                    String right_a_avg = object.optString( "right_a_avg" );
                    String left_s_avg = object.optString( "left_s_avg" );
                    String left_c_avg = object.optString( "left_c_avg" );
                    String left_a_avg = object.optString( "left_a_avg" );
                    String right_r1_mm = object.optString( "right_r1_mm" );
                    String right_r1_d = object.optString( "right_r1_d" );
                    String right_r1_ax = object.optString( "right_r1_ax" );
                    String right_r2_d = object.optString( "right_r2_d" );
                    String right_r2_mm = object.optString( "right_r2_mm" );
                    String left_r1_mm = object.optString( "left_r1_mm" );
                    String left_r1_d = object.optString( "left_r1_d" );
                    String left_r1_ax = object.optString( "left_r1_ax" );
                    String left_r2_d = object.optString( "left_r2_d" );
                    String left_r2_mm = object.optString( "left_r2_mm" );
                    right_r2_ax = object.optString( "right_r2_ax" );
                    right_avg_mm = object.optString( "right_avg_mm" );
                    right_avg_d = object.optString( "right_avg_d" );
                    right_kc = object.optString( "right_kc" );
                    left_r2_ax = object.optString( "left_r2_ax" );
                    left_avg_mm = object.optString( "left_avg_mm" );
                    left_avg_d = object.optString( "left_avg_d" );
                    left_kc = object.optString( "left_kc" );
                    pd = object.optString( "pd" );
                    ep_model = object.optString( "ep_model" );
                    brand = object.optString( "brand" );
                    software_version = object.optString( "software_version" );
                    Id = object.optString( "Id" );
                    odSph.setText( right_s_avg );
                    odCyl.setText( right_c_avg );
                    odAxial.setText( right_a_avg );
                    osSph.setText( left_s_avg );
                    osCyl.setText( left_c_avg );
                    osAxial.setText( left_a_avg );
                    odR1mm.setText( right_r1_mm );
                    odR2mm.setText( right_r2_mm );
                    odR1d.setText( right_r1_d );
                    odR2d.setText( right_r2_d );
                    odAX.setText( right_r1_ax );
                    osR1mm.setText( left_r1_mm );
                    osR2mm.setText( left_r2_mm );
                    osR1d.setText( left_r1_d );
                    osR2d.setText( left_r2_d );
                    osAX.setText( left_r1_ax );

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            EventBus.getDefault().postSticky( new Clear( 1 ) );
        }

        if (event.type == 1) {
            List<String> list = new ArrayList<>();
            //Toast.makeText( activity, "diopter验光仪蓝牙数据" + event.output, Toast.LENGTH_SHORT ).show();
            for (int i = 0; i < event.output.split( " " ).length; i++) {
                if (!TextUtils.isEmpty( event.output.split( " " )[i] )) {
                    try {
                        Log.e( "验光仪蓝牙数据------", event.output.split( " " )[i] );
                        list.add( event.output.split( " " )[i] );
                    } catch (Exception ignored) {
                    }
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Log.e( "验光仪------", list.get( i ) );
            }
//            if (list.size() != 8) {
            //Toast.makeText( activity, "数据异常，请重新打印", Toast.LENGTH_SHORT ).show();
//                return;
//            }
            if (list.size() >= 12) {
                odSph.setText( list.get( 5 ) );
                odCyl.setText( list.get( 6 ) );
                odAxial.setText( list.get( 7 ) );
                osSph.setText( list.get( 10 ) );
                osCyl.setText( list.get( 11 ) );
                osAxial.setText( list.get( 12 ) );
            }
            EventBus.getDefault().postSticky( new Clear( 1 ) );
        } else if (event.type == Constant.BLUE_RMK150) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < event.output.split( " " ).length; i++) {
                if (!UtilString.isEmpty( event.output.split( " " )[i] )) {
                    try {
                        list.add( event.output.split( " " )[i] );
                    } catch (Exception ignored) {
                    }
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Log.e( "RMK150验光仪------", list.get( i ) );
            }
            if (!UtilList.isEmpty( list )) {
                odSph.setText( list.get( 5 ) );
                odCyl.setText( list.get( 6 ) );
                odAxial.setText( list.get( 7 ) );
                osSph.setText( list.get( 10 ) );
                osCyl.setText( list.get( 11 ) );
                osAxial.setText( list.get( 12 ) );
            }
            list.clear();
            EventBus.getDefault().postSticky( new Clear( 1 ) );

        } else if (event.type == Constant.BLUE_BT578) {
            List<String> list = new ArrayList<>( Arrays.asList( event.output.split( "\r" ) ) );
            if (event.output.contains( "R" ) && event.output.contains( "L" )) {
                odSph.setText( list.get( 2 ).replace( " ", "" ) );
                odCyl.setText( list.get( 3 ).replace( " ", "" ) );
                odAxial.setText( list.get( 4 ).replace( " ", "" ) );
                osSph.setText( list.get( 7 ).replace( " ", "" ) );
                osCyl.setText( list.get( 8 ).replace( " ", "" ) );
                osAxial.setText( list.get( 9 ).replace( " ", "" ) );
                if (BaseApplication.currentBleDevice.getName().contains( "BT578" )) {
                    odR1d.setText( list.get( 14 ).replace( " ", "" ) );
                    odR1mm.setText( list.get( 15 ).replace( " ", "" ) );
                    odR2d.setText( list.get( 17 ).replace( " ", "" ) );
                    odR2mm.setText( list.get( 18 ).replace( " ", "" ) );
                    odAX.setText( list.get( 16 ).replace( " ", "" ) );
                    osR1d.setText( list.get( 25 ).replace( " ", "" ) );
                    osR1mm.setText( list.get( 26 ).replace( " ", "" ) );
                    osR2d.setText( list.get( 28 ).replace( " ", "" ) );
                    osR2mm.setText( list.get( 29 ).replace( " ", "" ) );
                    osAX.setText( list.get( 27 ).replace( " ", "" ) );
                }
            } else if (event.output.contains( "R" )) {
                odSph.setText( list.get( 2 ).replace( " ", "" ) );
                odCyl.setText( list.get( 3 ).replace( " ", "" ) );
                odAxial.setText( list.get( 4 ).replace( " ", "" ) );
                if (BaseApplication.currentBleDevice.getName().contains( "BT578" )) {
                    odR1d.setText( list.get( 8 ).replace( " ", "" ) );
                    odR1mm.setText( list.get( 9 ).replace( " ", "" ) );
                    odR2d.setText( list.get( 11 ).replace( " ", "" ) );
                    odR2mm.setText( list.get( 12 ).replace( " ", "" ) );
                    odAX.setText( list.get( 10 ).replace( " ", "" ) );
                }
            } else if (event.output.contains( "L" )) {
                osSph.setText( list.get( 2 ).replace( " ", "" ) );
                osCyl.setText( list.get( 3 ).replace( " ", "" ) );
                osAxial.setText( list.get( 4 ).replace( " ", "" ) );
                if (BaseApplication.currentBleDevice.getName().contains( "BT578" )) {
                    osR1d.setText( list.get( 8 ).replace( " ", "" ) );
                    osR1mm.setText( list.get( 9 ).replace( " ", "" ) );
                    osR2d.setText( list.get( 11 ).replace( " ", "" ) );
                    osR2mm.setText( list.get( 12 ).replace( " ", "" ) );
                    osAX.setText( list.get( 10 ).replace( " ", "" ) );
                }

            }


            EventBus.getDefault().postSticky( new Clear( 1 ) );
        } else if (event.type == 2) {
//            Toast.makeText( activity, event.output, Toast.LENGTH_SHORT ).show();
            String[] s = event.output.split( "," );
            odSph.setText( s[0].trim() );
            odCyl.setText( s[1].trim() );
            odAxial.setText( s[2].trim() );
            osSph.setText( s[3].trim() );
            osCyl.setText( s[4].trim() );
            osAxial.setText( s[5].trim() );
        } else if (event.type == 4) {
            Log.e( "DiopterFragment---", "onMessageEvent" );
        } else if (event.type == 5) {
            String ol = event.output.split( "OL" )[1].split( "OR" )[0];
            String or = event.output.split( "OL" )[1].split( "OR" )[1];
            odSph.setText( or.substring( 0, 6 ) );
            odCyl.setText( or.substring( 6, 12 ) );
            odAxial.setText( or.substring( 12, 15 ) );
            osSph.setText( ol.substring( 0, 6 ) );
            osCyl.setText( ol.substring( 6, 12 ) );
            osAxial.setText( ol.substring( 12, 15 ) );
        } else if (event.type == 7) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < event.output.split( "," ).length; i++) {
                if (!TextUtils.isEmpty( event.output.split( "," )[i] )) {
                    try {
                        System.out.println( event.output.split( "," )[i].split( "=" )[1] );
                        list.add( event.output.split( "," )[i].split( "=" )[1] );
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            odSph.setText( list.get( 1 ) );
            odCyl.setText( list.get( 2 ) );
            odAxial.setText( list.get( 3 ) );
            osSph.setText( list.get( 5 ) );
            osCyl.setText( list.get( 6 ) );
            osAxial.setText( list.get( 7 ) );

            EventBus.getDefault().postSticky( new Clear( 1 ) );
        } else if (event.type == Constant.BLUE_FA6500K) {
            String replaceString = DiopterDataUtil.replaceString( s );
            if (replaceString.contains( "R: S C A" ) && replaceString.contains( "L: S C A" )) {
                List<String> listRight = DiopterDataUtil.getListRight( replaceString );
                List<String> listLeft = DiopterDataUtil.getListLeft( replaceString );
                odSph.setText( listRight.get( 0 ).replace( " ", "" ) );
                odCyl.setText( listRight.get( 1 ).replace( " ", "" ) );
                odAxial.setText( listRight.get( 2 ).replace( " ", "" ) );
                osSph.setText( listLeft.get( 0 ).replace( " ", "" ) );
                osCyl.setText( listLeft.get( 1 ).replace( " ", "" ) );
                osAxial.setText( listLeft.get( 2 ).replace( " ", "" ) );
                if (replaceString.contains( "R: D MM A" )) {
                    //说明有角膜曲率数据
                    List<String> listRightRA = DiopterDataUtil.getListRightRA( replaceString );
                    odR1mm.setText( listRightRA.get( 1 ).replace( " ", "" ) );
                    odR1d.setText( listRightRA.get( 0 ).replace( " ", "" ) );
                    odAX.setText( listRightRA.get( 2 ).replace( " ", "" ) );
                    odR2mm.setText( listRightRA.get( 5 ).replace( " ", "" ) );
                    odR2d.setText( listRightRA.get( 4 ).replace( " ", "" ) );
                    List<String> listLeftRA = DiopterDataUtil.getListLeftRA( replaceString );
                    osR1mm.setText( listLeftRA.get( 1 ).replace( " ", "" ) );
                    osR1d.setText( listLeftRA.get( 0 ).replace( " ", "" ) );
                    osAX.setText( listLeftRA.get( 2 ).replace( " ", "" ) );
                    osR2mm.setText( listLeftRA.get( 5 ).replace( " ", "" ) );
                    osR2d.setText( listLeftRA.get( 4 ).replace( " ", "" ) );
                }
            } else if (replaceString.contains( "R: S C A" ) && !replaceString.contains( "L: S C A" )) {
                //只有右眼
                List<String> listRight = DiopterDataUtil.getListRightOnly( replaceString );
                odSph.setText( listRight.get( 0 ).replace( " ", "" ) );
                odCyl.setText( listRight.get( 1 ).replace( " ", "" ) );
                odAxial.setText( listRight.get( 2 ).replace( " ", "" ) );
                if (replaceString.contains( "R: D MM A" )) {
                    //说明有角膜曲率数据
                    List<String> listRightRA = DiopterDataUtil.getListRightRAOnly( replaceString );
                    odR1mm.setText( listRightRA.get( 1 ).replace( " ", "" ) );
                    odR1d.setText( listRightRA.get( 0 ).replace( " ", "" ) );
                    odAX.setText( listRightRA.get( 2 ).replace( " ", "" ) );
                    odR2mm.setText( listRightRA.get( 5 ).replace( " ", "" ) );
                    odR2d.setText( listRightRA.get( 4 ).replace( " ", "" ) );
                }
            } else if (!replaceString.contains( "R: S C A" ) && replaceString.contains( "L: S C A" )) {
                List<String> listLeft = DiopterDataUtil.getListLeftOnly( replaceString );
                osSph.setText( listLeft.get( 0 ).replace( " ", "" ) );
                osCyl.setText( listLeft.get( 1 ).replace( " ", "" ) );
                osAxial.setText( listLeft.get( 2 ).replace( " ", "" ) );
                if (replaceString.contains( "L: D MM A" )) {
                    //说明有角膜曲率数据
                    List<String> listLeftRA = DiopterDataUtil.getListLeftRAOnly( replaceString );
                    osR1mm.setText( listLeftRA.get( 1 ).replace( " ", "" ) );
                    osR1d.setText( listLeftRA.get( 0 ).replace( " ", "" ) );
                    osAX.setText( listLeftRA.get( 2 ).replace( " ", "" ) );
                    osR2mm.setText( listLeftRA.get( 5 ).replace( " ", "" ) );
                    osR2d.setText( listLeftRA.get( 4 ).replace( " ", "" ) );
                }
            }
            EventBus.getDefault().postSticky( new Clear( 1 ) );
        } else if (event.type == Constant.BLUE_NIDEKAR1_BTAR1) {
            DiopterDataUtil.setNIDEKAR1( event.output, odSph, odCyl, odAxial, osSph, osCyl, osAxial );
            EventBus.getDefault().postSticky( new Clear( 1 ) );
        } else if (event.type == Constant.BLUE_KR800) {
            DiopterDataUtil.setKR800( event.output, odSph, odCyl, odAxial, osSph, osCyl, osAxial );
            EventBus.getDefault().postSticky( new Clear( 1 ) );
        }else if (event.type == Constant.IP_VS100) {
            getScreenData( event.output );
        }
    }

    /**
     * 更新蓝牙数据
     *
     * @time 2020/12/1 15:07
     */
    private void notifyBLE(String uuid_service, String uuid_notify) throws JSONException {
        if (BaseApplication.currentBleDevice == null)
            return;

        BleManager.getInstance().notify(
                BaseApplication.currentBleDevice,
                uuid_service,
                uuid_notify,
                new BleNotifyCallback() {

                    private int length;

                    @Override
                    public void onNotifySuccess() {// 打开通知操作成功
                        LogUtil.e( "蓝牙读取---" + "diopater打开通知操作成功" );
                        if (!BaseApplication.strName.contains( "VisionScreener" )) {
                            BleManager.getInstance().getBluetoothGatt( BaseApplication.currentBleDevice ).requestMtu( 512 );
                        }
                        if (BaseApplication.strName.contains( "VisionScreener" )) {//美沃手持验光仪
                            String sendDataOne = BlueToothDataJson.getSendDataOne();
                            System.out.println( "发送第一条指令---" + sendDataOne );
                            FastBleLibUtil.write( sendDataOne, "00000001-1E3C-FAD4-74E2-97A033F1BFAA", "00000002-1E3C-FAD4-74E2-97A033F1BFAA" );
                            new Handler().postDelayed( () -> {
                                String sendData = BlueToothDataJson.getSendData( studentId, studentName, stuSex, stuBirth );
                                System.out.println( "发送第2条指令" + sendData );
                                FastBleLibUtil.writeTwo( sendData, "00000001-1E3C-FAD4-74E2-97A033F1BFAA", "00000002-1E3C-FAD4-74E2-97A033F1BFAA" );
                            }, 1000 );
                        }
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) { // 打开通知操作失败
                        bleCount++;
                        ToastUtil.showToastCenter( mContext, "蓝牙读取数据失败" );
                        LogUtil.e( "蓝牙读取---" + "diopater打开通知操作失败" + "---" + bleCount );
//                        if (bleCount == 3) {
//                            try {
//                                notifyBLE( "0000FFF0-0000-1000-8000-00805F9B34FB", "0000FFF1-0000-1000-8000-00805F9B34FB" );
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        } else if (bleCount == 2) {
//                            try {
//                                notifyBLE( "0003CDD0-0000-1000-8000-00805F9B0131", "0003CDD1-0000-1000-8000-00805F9B0131" );
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        } else {
//                            try {
//                                notifyBLE( "00001000-0000-1000-8000-00805f9b34fb", "00001002-0000-1000-8000-00805f9b34fb" );
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {// 打开通知后，设备发过来的数据将在这里出现
                        String dataChanged = new String( data );
                        length = length + dataChanged.length();
                        Log.e( "dataChanged---", dataChanged );
                        if (BaseApplication.strName.contains( "VisionScreener" )) {
                            s = new String( data );
                        } else if (BaseApplication.strName.contains( "BLECMN" )) {
                            testByte = UtilString.addBytes( testByte, data );
                            Log.e( "字节长度", "******:" + testByte.length );
                            if (testByte.length == 160) {
                                DiopterDataUtil.setCVSX( testByte, odSph, odCyl, odAxial, osSph, osCyl, osAxial );
                            }
                        } else {
                            s = s + new String( data );
//                            new Handler().postDelayed( new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (dataChanged.startsWith( "{" )) {
//                                        s = new String( data );
//                                    } else {
//
//                                    }
//                                }
//                            }, 100 );
                        }
                        if (BaseApplication.strName.contains( "RMK150" )) {
                            if (s.startsWith( "S No=" ) && s.endsWith( "E" )) {
                                Log.e( "RMK150蓝牙---", s );
                                EventBus.getDefault().postSticky( new BlueTooth( s, Constant.BLUE_RMK150 ) );
                            }

                        } else if (("BT-AR-1").equals( BaseApplication.strName ) && s.contains( "IDNIDEK/AR-1" )) { //尼德克AR-1设备
                            Log.e( "尼德克BT-AR-1蓝牙---", s );
                            new Handler().postDelayed( () -> {
                                EventBus.getDefault().postSticky( new BlueTooth( s, Constant.BLUE_NIDEKAR1_BTAR1 ) );
                            }, 500 );
                        } else if (("BT-AR-1").equals( BaseApplication.strName ) && s.contains( "IDNIDEK/ARK-1" )) { //尼德克ARK-1设备
                            Log.e( "尼德克BT-ARK-1蓝牙---", s );
                            new Handler().postDelayed( () -> {
                                EventBus.getDefault().postSticky( new BlueTooth( s, Constant.BLUE_NIDEKAR1_BTAR1 ) );
                            }, 500 );
                        } else if (("WSRMK8000-001").equals( BaseApplication.strName ) && s.contains( "software_version" )) { //雄博WSRMK8000设备
                            new Handler().postDelayed( () -> {
                                Log.e( "WSRMK8000蓝牙---", s );
                                Log.e( "dataChanged字节---", length + "" );
                                length = 0;
                                EventBus.getDefault().postSticky( new BlueTooth( s, Constant.BLUE_WSRMK8000 ) );
                            }, 200 );
                        } else {
                            new Handler().postDelayed( () -> {
                                if (!TextUtils.isEmpty( s )) {
                                    Log.e( "CharaChanged---", s );
//                                tvBleTest.setText( s );
                                    if (BleBlueToothUtils.getJSONType( s )) {//能解析成json
                                        JSONObject jsonObject;
                                        try {
                                            jsonObject = new JSONObject( s );
                                            if (BaseApplication.strName.contains( "VisionScreener" )) {
                                                if (UtilString.isEmpty( jsonObject.getJSONArray( "OS" ).toString() )) {
                                                    return;
                                                }
                                                EventBus.getDefault().postSticky( new BlueTooth( s, 110 ) );

                                            } else {
                                                EventBus.getDefault().postSticky( new BlueTooth( s, 110 ) );
                                            }

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    } else if (s.contains( "NIDEK" )) {
                                        EventBus.getDefault().postSticky( new BlueTooth( s, 5 ) );
                                    } else if (s.contains( "A\rR" ) || s.contains( "A\rL" )) { //AR- 5.25         L- 5.50
                                        EventBus.getDefault().postSticky( new BlueTooth( s, Constant.BLUE_BT578 ) );
                                    } else if (s.contains( "KR-800" ) ) { //拓普康KR800验光仪
                                        EventBus.getDefault().postSticky( new BlueTooth( s, Constant.BLUE_KR800 ) );
                                    }else if (s.startsWith( "<" )) {
                                        EventBus.getDefault().postSticky( new BlueTooth( s, 7 ) );
                                    } else if (s.contains( "SCHOOL:" )) {
                                        //新缘FA6500K验光仪
                                        EventBus.getDefault().postSticky( new BlueTooth( s, Constant.BLUE_FA6500K ) );
                                    } else if (s.equals( "#!<DATY00#!>" )) {
                                        //新增拓普康蓝牙
                                        s = "";
                                        FastBleLibUtil.write( "#!<REFR01#!>", "0000ffe0-0000-1000-8000-00805f9b34fb", "0000ffe1-0000-1000-8000-00805F9B34FB" );
                                    } else if (s.startsWith( "#!<REFR" ) && s.endsWith( "#!>" )) {
                                        try {
                                            String s_r = s.substring( 26, 32 );//S球镜
                                            String c_r = s.substring( 32, 38 ); //C柱镜
                                            String a_r = s.substring( 38, 41 ); //A轴位
                                            odSph.setText( s_r );
                                            odCyl.setText( c_r );
                                            odAxial.setText( a_r );
                                        } catch (Exception ignored) {

                                        }
                                        s = "";
                                        FastBleLibUtil.write( "#!<REFL01#!>", "0000ffe0-0000-1000-8000-00805f9b34fb", "0000ffe1-0000-1000-8000-00805F9B34FB" );
                                    } else if (s.startsWith( "#!<REFL" ) && s.endsWith( "#!>" )) {
                                        try {
                                            String s_l = s.substring( 26, 32 );//S球镜
                                            String c_l = s.substring( 32, 38 ); //C柱镜
                                            String a_l = s.substring( 38, 41 ); //A轴位
                                            osSph.setText( s_l );
                                            osCyl.setText( c_l );
                                            osAxial.setText( a_l );
                                        } catch (Exception ignored) {

                                        }
                                        s = "";
                                    } else { //包括RM9000-C285蓝牙模块
                                        if (s.startsWith( "S No=" )) {
                                            EventBus.getDefault().postSticky( new BlueTooth( s, 1 ) );
                                        }
                                    }
                                }
                            }, 1000 );
                        }

                    }
                } );
    }


    public static DiopterFragment newInstance(String studentId, String taskId, String type) {
        Bundle args = new Bundle();
        args.putString( "studentId", studentId );
        args.putString( "taskId", taskId );
        args.putString( "type", type );
        DiopterFragment fragment = new DiopterFragment();
        fragment.setArguments( args );
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_diopter;
    }

    @Override
    protected void initView() {
        progressDialog = new ProgressDialog( activity );
        progressDialog.setCancelable( false );
        progressDialog.setMessage( "数据上传中..." );

        initList();
        odR1mm.addTextChangedListener( new Watcher( odR1mm, tvOdR1mm, 5, 10 ) );
        osR1mm.addTextChangedListener( new Watcher( osR1mm, tvOsR1mm, 5, 10 ) );
        odR2mm.addTextChangedListener( new Watcher( odR2mm, tvOdR2mm, 5, 10 ) );
        osR2mm.addTextChangedListener( new Watcher( osR2mm, tvOsR2mm, 5, 10 ) );
        odR1d.addTextChangedListener( new Watcher( odR1d, tvOdR1d, 33.75, 67.50 ) );
        osR1d.addTextChangedListener( new Watcher( osR1d, tvOsR1d, 33.75, 67.50 ) );
        odR2d.addTextChangedListener( new Watcher( odR2d, tvOdR2d, 33.75, 67.50 ) );
        osR2d.addTextChangedListener( new Watcher( osR2d, tvOsR2d, 33.75, 67.50 ) );
        odAX.addTextChangedListener( new Watcher( odAX, tvOdAX, 0, 180 ) );
        osAX.addTextChangedListener( new Watcher( osAX, tvOsAX, 0, 180 ) );

        //轴位监听
        odAxial.addTextChangedListener( new WatcherZW( odAxial, tvOdAxial ) );
        osAxial.addTextChangedListener( new WatcherZW( osAxial, tvoSAxial ) );

        pvOptions_zhujing = new OptionsPickerBuilder( activity, (options1, option2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            String tx = options3Items.get( options1 )
                    + options2Items.get( option2 );
            if (!currentView.getText().toString().trim().equals( tx )) {
                manual = "1";
            }
            currentView.setText( tx );

            changeBottomSave();
        } ).build();
        pvOptions_zhujing.setNPicker( options3Items, options2Items, null );

        pvOptions_qiujing = new OptionsPickerBuilder( activity, (options1, option2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            String tx = options1Items.get( options1 )
                    + options2Items.get( option2 );
            if (!currentView.getText().toString().trim().equals( tx )) {
                manual = "1";
            }
            currentView.setText( tx );
            changeBottomSave();
        } ).build();
        pvOptions_qiujing.setNPicker( options1Items, options2Items, null );

        refreshLayout.setPrimaryColors( 0xffffffff, 0xff55B8A9 );
        refreshLayout.setEnableLoadMore( false );
        refreshLayout.setOnRefreshListener( refreshLayout -> {
            mContext.stopService( new Intent( mContext, SocketService.class ) );
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mContext.startForegroundService( new Intent( mContext, SocketService.class ) );
            } else {
                mContext.startService( new Intent( mContext, SocketService.class ) );
            }
            new Handler().postDelayed( () -> refreshLayout.finishRefresh( true ), 1000 );
        } );


    }


    @OnClick(R.id.btn_connect_device)
    void btn_connect_device() {
        startActivity( DeviceTypeActivity.class );
    }

    @OnClick(R.id.odSph)
    void odSph() {
        hintKeyBoard( odSph );
        showCurrentQiuJingData( odSph.getText().toString().trim() );
        pvOptions_qiujing.show();
        currentView = odSph;
    }

    @OnClick(R.id.osSph)
    void osSph() {
        hintKeyBoard( osSph );
        showCurrentQiuJingData( osSph.getText().toString().trim() );
        pvOptions_qiujing.show();
        currentView = osSph;
    }


    @OnClick(R.id.odCyl)
    void odCyl() {
        hintKeyBoard( odCyl );
        showCurrentZhuJingData( odCyl.getText().toString().trim() );
        pvOptions_zhujing.show();
        currentView = odCyl;
    }


    @OnClick(R.id.osCyl)
    void osCyl() {
        hintKeyBoard( osCyl );
        showCurrentZhuJingData( osCyl.getText().toString().trim() );
//        if (!TextUtils.isEmpty( osCyl.getText().toString() )) {
//            if (osCyl.getText().toString().trim().equals( "." )) {
//                String[] temp = osCyl.getText().toString().split( "\\." );
//                pvOptions_zhujing.setSelectOptions( Math.abs( Integer.parseInt( temp[0] ) ), Integer.parseInt( temp[1] ) / 25 );
//            }
//        }
        pvOptions_zhujing.show();
        currentView = osCyl;
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        Log.e( "currentEditId===", BaseApplication.currentEditId + "" );
        if (TextUtils.isEmpty( BaseApplication.currentEditId )) {
            submitData( "save", false );
            //saveInfo( false );
            return;
        }
        //修改学生屈光信息
        // update( false );
        submitData( "update", false );
    }

    @OnClick(R.id.tv_vision)
    void tv_vision() {
        Log.e( "currentEditId===", BaseApplication.currentEditId + "" );
        if (TextUtils.isEmpty( BaseApplication.currentEditId )) {
            submitData( "save", true );
            //saveInfo( false );
            return;
        }
        //修改学生屈光信息
        // update( false );
        submitData( "update", true );
    }

    @Override
    protected void initData() {
        if (!EventBus.getDefault().isRegistered( this )) {
            EventBus.getDefault().register( this );
        }
        strName = BaseApplication.strName;
        strAddress = BaseApplication.strAddress;
        assert getArguments() != null;
        studentId = getArguments().getString( "studentId" );
        taskId = getArguments().getString( "taskId" );
        taskType = getArguments().getString( "type" );

    }

    /**
     * 获取伟伦v100手持筛查仪数据并处理
     */
    void getScreenData(String host) {
        try {
            showProgressDialog();
            HttpDigestUtils httpDigestUtils = new HttpDigestUtils( getContext() );

            httpDigestUtils.setOnCallback( new HttpDigestUtils.CallBackResponse() {
                @SuppressLint("DefaultLocale")
                @Override
                public void onSuccess(String response) {
                    String[] split = response.split( "\n" );
                    if (split.length < 2) {
                        ToastUtil.showToast( getContext(), "请先进行屈光筛查" );
                        Objects.requireNonNull( getActivity() ).runOnUiThread( () -> dismissProgressDialog() );
                        return;
                    }
                    HashMap<String, String> hashMap = new HashMap<>();
                    String[] keys = split[0].split( "," );
                    String[] values = split[1].split( ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1 );
                    for (int i = 0; i <= keys.length - 1; i++) {
                        hashMap.put( keys[i], values[i] );
                    }
                    Objects.requireNonNull( getActivity() ).runOnUiThread( () -> {

                        odSph.setText( String.format( "%+.2f", Float.valueOf( Objects.requireNonNull( hashMap.get( "格式化右眼 DS" ) ) ) ) );
                        osSph.setText( String.format( "%+.2f", Float.valueOf( Objects.requireNonNull( hashMap.get( "格式化左眼 DS" ) ) ) ) );

                        odCyl.setText( String.format( "%+.2f", Float.valueOf( Objects.requireNonNull( hashMap.get( "格式化右眼 DC" ) ) ) ) );
                        osCyl.setText( String.format( "%+.2f", Float.valueOf( Objects.requireNonNull( hashMap.get( "格式化左眼 DC" ) ) ) ) );

                        if (TextUtils.isEmpty( hashMap.get( "格式化右眼散光轴" ) )) {
                            odAxial.setText( "0" );
                        } else {
                            odAxial.setText( Objects.requireNonNull( hashMap.get( "格式化右眼散光轴" ) ).replace( "@", "" ).replace( "°", "" ) );
                        }

                        if (TextUtils.isEmpty( hashMap.get( "格式化左眼散光轴" ) )) {
                            osAxial.setText( "0" );
                        } else {
                            osAxial.setText( Objects.requireNonNull( hashMap.get( "格式化左眼散光轴" ) ).replace( "@", "" ).replace( "°", "" ) );
                        }
                        dismissProgressDialog();
                    } );
                }

                @Override
                public void onFail() {
                    Objects.requireNonNull( getActivity() ).runOnUiThread( () -> dismissProgressDialog() );
                }
            } );

            httpDigestUtils.getScreenData( "https://" + host + "/db/SpotResultsExtended.csv" );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        getInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (BaseApplication.lastFragment == 1) {

        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint( isVisibleToUser );
        LogUtil.e( "setUserVisibleHint---", isVisibleToUser + "---DiopterFragment---" + getUserVisibleHint() );
        if (isVisibleToUser) {
            BaseApplication.lastFragment = 1;
            if (BaseApplication.currentBleDevice == null) {
                return;
            }
            bleCount = 0;
            LogUtil.e( "strName----" + BaseApplication.strName );
            if (BaseApplication.strName.contains( "VisionScreener" )) {
                //美沃手持验光仪
                try {
                    notifyBLE( "00000001-1E3C-FAD4-74E2-97A033F1BFAA", "00000002-1E3C-FAD4-74E2-97A033F1BFAA" );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (BaseApplication.strName.contains( "WH-BLE" ) || BaseApplication.strName.contains( "WSRMK8000-001" )) {
                try {
                    notifyBLE( "0003CDD0-0000-1000-8000-00805F9B0131", "0003CDD1-0000-1000-8000-00805F9B0131" );
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else if (BaseApplication.strName.contains( "FA-6500" )) {
                try {
                    //新缘FA6500K验光仪
                    notifyBLE( "0000FFF0-0000-1000-8000-00805F9B34FB", "0000FFF1-0000-1000-8000-00805F9B34FB" );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (BaseApplication.strName.contains( "BLECMN" )) {
                try {
                    //CVSX 视力筛选仪 目乐医疗
                    notifyBLE( "0000fff2-0000-1000-8000-00805f9b34fb", "00009997-0000-1000-8000-00805f9b34fb" );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (!BaseApplication.strName.contains( "AXL-800" )) {
                try {
                    notifyBLE( "0000ffe0-0000-1000-8000-00805f9b34fb", "0000ffe1-0000-1000-8000-00805f9b34fb" );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
//        BaseApplication.lastFragment = 1;
//        if (getUserVisibleHint()) {
////            getInfo();
//            BleManager.getInstance().notify(
//                    BaseApplication.currentBleDevice,
//                    "0000ffe0-0000-1000-8000-00805f9b34fb",
//                    "0000ffe1-0000-1000-8000-00805f9b34fb",
//                    new BleNotifyCallback() {
//                        @Override
//                        public void onNotifySuccess() {
//                            // 打开通知操作成功
//                            System.out.println( "setUserVisibleHint---onNotifySuccess---diopater打开通知操作成功" );
//                        }
//
//                        @Override
//                        public void onNotifyFailure(BleException exception) {
//                            // 打开通知操作失败
//                        }
//
//                        @Override
//                        public void onCharacteristicChanged(byte[] data) {
//                            // 打开通知后，设备发过来的数据将在这里出现
//                            s = s + new String( data );
//                            new Handler().postDelayed( () -> {
//                                System.out.println( s.equals( "#!<DATY00#!>" ) );
//                                if (!TextUtils.isEmpty( s )) {
//                                    Log.e( "VisibleHint----", s );
//                                    if (BleBlueToothUtils.getJSONType( s )) {
//                                        //能解析成json
//                                        EventBus.getDefault().postSticky( new BlueTooth( s, 110 ) );
//                                    } else if (s.contains( "NIDEK" )) {
//                                        EventBus.getDefault().postSticky( new BlueTooth( s, 5 ) );
//                                    } else if (s.equals( "#!<DATY00#!>" )) {
//                                        s = "";
//                                        FastBleLibUtil.write( "#!<REFR01#!>", "0000ffe0-0000-1000-8000-00805f9b34fb", "0000ffe1-0000-1000-8000-00805F9B34FB" );
//                                    } else if (s.startsWith( "#!<REFR" ) && s.endsWith( "#!>" )) {
//                                        try {
//                                            String s_r = s.substring( 26, 32 );//S球镜
//                                            String c_r = s.substring( 32, 38 ); //C柱镜
//                                            String a_r = s.substring( 38, 41 ); //A轴位
//                                            odSph.setText( s_r );
//                                            odCyl.setText( c_r );
//                                            odAxial.setText( a_r );
//                                        } catch (Exception ignored) {
//
//                                        }
//                                        s = "";
//                                        FastBleLibUtil.write( "#!<REFL01#!>", "0000ffe0-0000-1000-8000-00805f9b34fb", "0000ffe1-0000-1000-8000-00805F9B34FB" );
//                                    } else if (s.startsWith( "#!<REFL" ) && s.endsWith( "#!>" )) {
//                                        try {
//                                            String s_l = s.substring( 26, 32 );//S球镜
//                                            String c_l = s.substring( 32, 38 ); //C柱镜
//                                            String a_l = s.substring( 38, 41 ); //A轴位
//                                            osSph.setText( s_l );
//                                            osCyl.setText( c_l );
//                                            osAxial.setText( a_l );
//                                        } catch (Exception ignored) {
//
//                                        }
//                                        s = "";
//                                    } else {
//                                        EventBus.getDefault().postSticky( new BlueTooth( s, 1 ) );
//                                    }
//                                }
//                            }, 1000 );
//                        }
//                    } );
//
//        } else {
//            //界面不可见 相当于onpause
//            BleManager.getInstance().removeNotifyCallback( BaseApplication.currentBleDevice, "0000ffe1-0000-1000-8000-00805f9b34fb" );
//        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated( view, savedInstanceState );
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach( context );
        activity = (Activity) context;//保存Context引用
    }


    @Override
    public void onDestroy() {
//        activity.unregisterReceiver(connectDevices);
        EventBus.getDefault().unregister( this );
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();

        LogUtil.e( "DiopterFragment---", "onPause" );
    }

    @Override
    public void onStop() {
        super.onStop();
//        BleManager.getInstance().cancelScan();
//        BleManager.getInstance().destroy();
        LogUtil.e( "DiopterFragment---", "onStop" );
    }

    /**
     * 接口获取之前保存的屈光数据
     *
     * @time 2020/5/27 9:19
     */
    private void getInfo() {
        RestProxy.getInstance().getStudentInfoQG( studentId + "", taskId, new Observer<StudentInfoResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StudentInfoResponse studentInfoResponse) {
                try {
                    BaseApplication.currentEditId = studentInfoResponse.data.id;
                    odSph.setText( studentInfoResponse.data.dpOdSph == null ? "" : studentInfoResponse.data.dpOdSph );
                    odCyl.setText( studentInfoResponse.data.dpOdCyl == null ? "" : studentInfoResponse.data.dpOdCyl );
                    odAxial.setText( studentInfoResponse.data.dpOdAxial == null ? "" : studentInfoResponse.data.dpOdAxial );
                    osSph.setText( studentInfoResponse.data.dpOsSph == null ? "" : studentInfoResponse.data.dpOsSph );
                    osCyl.setText( studentInfoResponse.data.dpOsCyl == null ? "" : studentInfoResponse.data.dpOsCyl );
                    osAxial.setText( studentInfoResponse.data.dpOsAxial == null ? "" : studentInfoResponse.data.dpOsAxial );
                    odR1mm.setText( studentInfoResponse.data.orbRightR1Mm == null ? "" : studentInfoResponse.data.orbRightR1Mm );
                    odR2mm.setText( studentInfoResponse.data.orbRightR2Mm == null ? "" : studentInfoResponse.data.orbRightR2Mm );
                    odR1d.setText( studentInfoResponse.data.orbRightR1D == null ? "" : studentInfoResponse.data.orbRightR1D );
                    odR2d.setText( studentInfoResponse.data.orbRightR2D == null ? "" : studentInfoResponse.data.orbRightR2D );
                    odAX.setText( studentInfoResponse.data.orbRightR1Ax == null ? "" : studentInfoResponse.data.orbRightR1Ax );
                    osR1mm.setText( studentInfoResponse.data.orbLeftR1Mm == null ? "" : studentInfoResponse.data.orbLeftR1Mm );
                    osR2mm.setText( studentInfoResponse.data.orbLeftR2Mm == null ? "" : studentInfoResponse.data.orbLeftR2Mm );
                    osR1d.setText( studentInfoResponse.data.orbLeftR1D == null ? "" : studentInfoResponse.data.orbLeftR1D );
                    osR2d.setText( studentInfoResponse.data.orbLeftR2D == null ? "" : studentInfoResponse.data.orbLeftR2D );
                    osAX.setText( studentInfoResponse.data.orbLeftR1Ax == null ? "" : studentInfoResponse.data.orbLeftR1Ax );

                    stuName.setText( String.format( "%s  %s", studentInfoResponse.data.fullClassName, studentInfoResponse.data.studentName ) );
                    studentName = studentInfoResponse.data.studentName;

                    stuSex = studentInfoResponse.data.sex;
                    stuBirth = studentInfoResponse.data.birth;
                    tv_examiner.setText( String.format( "检查人:%s", studentInfoResponse.data.checker ) );
                    tvExaminerTime.setText( String.format( "检查时间:%s", studentInfoResponse.data.checkedTime ) );
//                    odSph.setText( "-4.00" );
//                    odCyl.setText( "-0.75" );
//                    odAxial.setText( "+3" );
//                    osSph.setText( "-1.00" );
//                    osCyl.setText( "-0.50" );
//                    osAxial.setText( "+160" );

                    if (!TextUtils.isEmpty( studentInfoResponse.data.remark )) {
//                    if (studentInfoResponse.data.diopterRemark.startsWith("D")) {
//                        tv_remark.setText("其他");
//                        edt_remark.setText(studentInfoResponse.data.diopterRemark.substring(1, studentInfoResponse.data.diopterRemark.length()));
//                        edt_remark.setVisibility(View.VISIBLE);
//                    } else {
                        tv_remark.setTextColor( ContextCompat.getColor( activity, R.color.lightBlack ) );
                        tv_remark.setText( studentInfoResponse.data.remark );
                        isEmptyRemark = false;

//                    }
                    } else {
                        isEmptyRemark = true;
                    }
                    changeBottomSave();
                } catch (Exception e) {
                    e.printStackTrace();
                    activity.runOnUiThread( () -> Toast.makeText( activity, "服务器数据异常", Toast.LENGTH_SHORT ).show() );
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, activity );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(Clear clear) {
        if (clear.clear == 1) {
            s = "";
        }
    }

    //屈光度异常弹窗

    private void showQualifiedDialog() {
//        if (mQualifiedDialog == null) {
        mQualifiedDialog = QualifiedDialog.newInstance( "屈光与视力不匹配，建议重新检查" );
        mQualifiedDialog.show( getChildFragmentManager(), "mQualifiedDialog" );
        mQualifiedDialog.setmListener( new QualifiedDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                mQualifiedDialog.dismiss();
            }

            @Override
            public void onCancel() {
                activity.finish();
            }
        } );
    }

    @OnClick(R.id.btn_remark)
    void btn_remark() {
        showRemarkDialog();
    }

    /**
     * 备注弹窗
     *
     * @time 2020/5/27 9:17
     */
    private void showRemarkDialog() {
        if (mRemarkDialog == null) {
            mRemarkDialog = RemarkDialog.newInstance( true, false );
            mRemarkDialog.show( getChildFragmentManager(), "mRemarkDialog" );
            mRemarkDialog.setmListener( (reason, type) -> {

                if (!UtilString.isEmpty( reason )) {
                    isEmptyRemark = false;
                    tv_remark.setTextColor( ContextCompat.getColor( activity, R.color.lightBlack ) );
                    tv_remark.setText( reason );
                    changeBottomSave();
                } else {
                    //清空
                    isEmptyRemark = true;
                    tv_remark.setTextColor( ContextCompat.getColor( activity, R.color.ffd3dcdc ) );
                    tv_remark.setText( "备注：无检测数据必填，否则视为未筛查" );
                    changeBottomSave();
                }

                mRemarkDialog.dismiss();
            } );
        } else if (!mRemarkDialog.isAdded() && !mRemarkDialog.isShowing()) {
            mRemarkDialog.show( getChildFragmentManager(), "mRemarkDialog" );
        }
    }

    /**
     * 检查参数
     *
     * @time 2020/4/8 16:15
     */
    private void submitData(String submitType, boolean isNext) {
        /*
         * 球镜正则表达式：从+- 00.00~+-20.00
         */
        String regQJ = "^[+-](0?\\d.\\d{2}|1\\d.\\d{2}|20.00)$";
        /*
         * 柱镜正则表达式：从- 00.00~-20.00
         */
        String regZJ = "^-(0?\\d.\\d{2}|1\\d.\\d{2}|20.00)|(\\+0?0.00)$";

        /*
         * 新轴位正则表达式：整数，且在0~180之间，支持+000，+012，+002这样的格式
         */
        String regZW = "^[+]?(0?0?\\d|0?\\d{2}|1[0-7]\\d|180)$";

        //球镜数组
        String[] strs1 = new String[]{odSph.getText().toString(), osSph.getText().toString()};
        //柱镜数组
        String[] strs2 = new String[]{odCyl.getText().toString(), osCyl.getText().toString()};
        //轴位数组
        String[] strs3 = new String[]{odAxial.getText().toString(), osAxial.getText().toString()};
        String[] rightString = new String[]{odSph.getText().toString().trim(), odCyl.getText().toString().trim(), odAxial.getText().toString().trim()};
        String[] leftString = new String[]{osSph.getText().toString().trim(), osCyl.getText().toString().trim(), osAxial.getText().toString().trim()};
        String remark = "";
        if (TextUtils.isEmpty( odSph.getText().toString() ) && TextUtils.isEmpty( osSph.getText().toString() ) && TextUtils.isEmpty( odCyl.getText().toString() ) && TextUtils.isEmpty( osCyl.getText().toString() ) && TextUtils.isEmpty( odAxial.getText().toString() ) && TextUtils.isEmpty( osAxial.getText().toString() )) {
            if (isEmptyRemark) {
                Toast.makeText( activity, "请填写球柱镜轴位数据或者备注", Toast.LENGTH_SHORT ).show();
            } else {
                remark = tv_remark.getText().toString().trim();
                requestInterface( submitType, isNext, remark );
            }
        } else {
            if (!isEmptyRemark) {
                remark = tv_remark.getText().toString().trim();
            } else {
//                if (TextUtils.isEmpty( odSph.getText().toString() ) || TextUtils.isEmpty( osSph.getText().toString() ) || TextUtils.isEmpty( odCyl.getText().toString() ) || TextUtils.isEmpty( osCyl.getText().toString() ) || TextUtils.isEmpty( odAxial.getText().toString() ) || TextUtils.isEmpty( osAxial.getText().toString() )) {
//                    Toast.makeText( activity, "请检查屈光参数或备注", Toast.LENGTH_SHORT ).show();
//                    return;
//                }
                for (String str : strs1) {
                    if (TextUtils.isEmpty( str )) {
                        Toast.makeText( activity, "球镜数据不能为空", Toast.LENGTH_SHORT ).show();
                        return;
                    }
                }

                for (String str : strs2) {
                    if (TextUtils.isEmpty( str )) {
                        Toast.makeText( activity, "柱镜数据不能为空", Toast.LENGTH_SHORT ).show();
                        return;
                    }
                }

                for (String str : strs3) {
//                    if (!TextUtils.isEmpty( str ) && !str.matches( regZW )) {
                    if (TextUtils.isEmpty( str )) {
                        Toast.makeText( activity, "轴位数据不能为空", Toast.LENGTH_SHORT ).show();
                        return;
                    }
                }
            }


            String odR1m = odR1mm.getText().toString().trim();
            String osR1m = osR1mm.getText().toString().trim();
            String odR1dd = odR1d.getText().toString().trim();
            String osR1dd = osR1d.getText().toString().trim();
            String odR2m = odR2mm.getText().toString().trim();
            String osR2m = osR2mm.getText().toString().trim();
            String odR2dd = odR2d.getText().toString().trim();
            String osR2dd = osR2d.getText().toString().trim();
            String odAXx = odAX.getText().toString().trim();
            String osAXx = osAX.getText().toString().trim();
            if (DiopterDataUtil.checkR1MM( odR1mm, odR1m ) && DiopterDataUtil.checkR1MM( osR1mm, osR1m ) && DiopterDataUtil.checkR1MM( odR2mm, odR2m ) && DiopterDataUtil.checkR1MM( osR2mm, osR2m )
                    && DiopterDataUtil.checkR1D( odR1d, odR1dd ) && DiopterDataUtil.checkR1D( osR1d, osR1dd ) && DiopterDataUtil.checkR1D( odR2d, odR2dd ) && DiopterDataUtil.checkR1D( osR2d, osR2dd )
                    && DiopterDataUtil.checkAX( odAX, odAXx ) && DiopterDataUtil.checkAX( osAX, osAXx )) {
                requestInterface( submitType, isNext, remark );
            } else {
                Toast.makeText( activity, "角膜曲率格式错误, 无法保存", Toast.LENGTH_SHORT ).show();

            }


        }

    }

    private void requestInterface(String submitType, boolean isNext, String remark) {
        String ygyDevice = PreferencesHelper.getInstance().getString( activity, "ygyDevice" );
        LogUtil.e( "ygy设备类型----", ygyDevice );
        Map<String, Object> map = new HashMap<>();//body  map
        map.put( "studentId", studentId + "" );
        map.put( "dpOdSph", odSph.getText().toString().trim() );
        map.put( "dpOsSph", osSph.getText().toString().trim() );
        map.put( "dpOdCyl", odCyl.getText().toString().trim() );
        map.put( "dpOsCyl", osCyl.getText().toString().trim() );
        map.put( "dpOdAxial", odAxial.getText().toString().trim() );
        map.put( "dpOsAxial", osAxial.getText().toString().trim() );
        map.put( "orbRightR1Mm", odR1mm.getText().toString().trim() );
        map.put( "orbRightR1D", odR1d.getText().toString().trim() );
        map.put( "orbRightR1Ax", odAX.getText().toString().trim() );
        map.put( "orbRightR2Mm", odR2mm.getText().toString().trim() );
        map.put( "orbRightR2D", odR2d.getText().toString().trim() );
        map.put( "orbLeftR1Mm", osR1mm.getText().toString().trim() );
        map.put( "orbLeftR1D", osR1d.getText().toString().trim() );
        map.put( "orbLeftR1Ax", osAX.getText().toString().trim() );
        map.put( "orbLeftR2Mm", osR2mm.getText().toString().trim() );
        map.put( "orbLeftR2D", osR2d.getText().toString().trim() );
        map.put( "taskId", taskId );
        map.put( "dpRemark", remark );
        map.put( "source", manual );
        map.put( "orbRightR2Ax", right_r2_ax );
        map.put( "orbRightAvgMm", right_avg_mm );
        map.put( "orbRightAvgD", right_avg_d );
        map.put( "orbRightKc", right_kc );
        map.put( "orbLeftR2Ax", left_r2_ax );
        map.put( "orbLeftAvgMm", left_avg_mm );
        map.put( "orbLeftAvgD", left_avg_d );
        map.put( "orbLeftKc", left_kc );
        map.put( "pd", pd );
        map.put( "epModel", ep_model );
        map.put( "brand", brand );
        map.put( "softwareVersion", software_version );
        map.put( "autoRefractorId", Id );
        map.put( "device", ygyDevice );

        if ("update".equals( submitType )) {
            map.put( "id", BaseApplication.currentEditId );
            RestProxy.getInstance().updateStudentSecondInfo( map, new Observer<QualifiedResponse>() {
                @Override
                public void onSubscribe(Disposable d) {
//                    btn_confirm.setClickable( false );
                    progressDialog.show();
                }

                @Override
                public void onNext(QualifiedResponse qualifiedResponse) {
                    if (DiopterFragment.this.isAdded()) {
                        progressDialog.dismiss();
                    }
                    if (qualifiedResponse.data) {
                        showQualifiedDialog();
                    } else {
                        Toast.makeText( activity, "保存成功", Toast.LENGTH_SHORT ).show();
                        if (isNext) {
                            //进入视力检查
                            if ("1".equals( taskType )) {
                                ((StudentDetailActivity) activity).setmViewPager( 0 );
                            } else if ("3".equals( taskType )) {
                                ((StudentDetailOtherActivity) activity).setmViewPager( 0 );
                            }
                            EventBus.getDefault().postSticky( new StartVision( 0 ) );
                            getInfo();
                        } else {
                            activity.finish();
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {
                    progressDialog.dismiss();
                    NetUtil.onError( e, activity );
//                    btn_confirm.setClickable( true );
                }

                @Override
                public void onComplete() {
//                    btn_confirm.setClickable( true );
                }
            } );
        } else if ("save".equals( submitType )) {
            RestProxy.getInstance().saveStudentSecondInfo( map, new Observer<QualifiedResponse>() {
                @Override
                public void onSubscribe(Disposable d) {
//                    btn_confirm.setClickable( false );
                    progressDialog.show();
                }

                @Override
                public void onNext(QualifiedResponse qualifiedResponse) {
                    if (DiopterFragment.this.isAdded()) {
                        progressDialog.dismiss();
                    }
                    if (qualifiedResponse.data) {
                        showQualifiedDialog();
                    } else {
                        Toast.makeText( activity, "保存成功", Toast.LENGTH_SHORT ).show();
                        if (isNext) {
                            if ("1".equals( taskType )) {
                                ((StudentDetailActivity) activity).setmViewPager( 0 );
                            } else if ("3".equals( taskType )) {
                                ((StudentDetailOtherActivity) activity).setmViewPager( 0 );
                            }
                            EventBus.getDefault().postSticky( new StartVision( 0 ) );
                            getInfo();
                        } else {
                            activity.finish();
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {
                    progressDialog.dismiss();
                    NetUtil.onError( e, activity );
//                    btn_confirm.setClickable( true );
                }

                @Override
                public void onComplete() {
//                    btn_confirm.setClickable( true );
                }
            } );
        }
    }


    @OnClick({R.id.odAxial, R.id.osAxial, R.id.odR1mm, R.id.osR1mm, R.id.odR1d, R.id.osR1d, R.id.odR2mm, R.id.osR2mm, R.id.odR2d, R.id.osR2d, R.id.odAX, R.id.osAX})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.odAxial:
                requestFocusKeyBoard( odAxial );
                break;
            case R.id.osAxial:
                requestFocusKeyBoard( osAxial );
                break;
            case R.id.odR1mm:
                requestFocus( odR1mm );
                break;
            case R.id.osR1mm:
                requestFocus( osR1mm );
                break;
            case R.id.odR1d:
                requestFocus( odR1d );
                break;
            case R.id.osR1d:
                requestFocus( osR1d );
                break;
            case R.id.odR2mm:
                requestFocus( odR2mm );
                break;
            case R.id.osR2mm:
                requestFocus( osR2mm );
                break;
            case R.id.odR2d:
                requestFocus( odR2d );
                break;
            case R.id.osR2d:
                requestFocus( osR2d );
                break;
            case R.id.odAX:
                requestFocus( odAX );
                break;
            case R.id.osAX:
                requestFocus( osAX );
                break;
        }
    }

    class Watcher implements TextWatcher {

        EditText etTextView;
        TextView textView;
        double start, end;

        Watcher(EditText odR1mm, TextView tvOdR1mm, double start, double end) {
            this.etTextView = odR1mm;
            this.textView = tvOdR1mm;
            this.start = start;
            this.end = end;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            String trim = etTextView.getText().toString().trim();
            if (!UtilString.isEmpty( trim )) {
                if (Double.parseDouble( trim ) < start || Double.parseDouble( trim ) > end) {
                    textView.setVisibility( View.VISIBLE );
                    tvVision.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_grey_stroke_25 ) );
                    tvVision.setTextColor( ContextCompat.getColor( activity, R.color.ffd3dcdc ) );
                    btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_light_blue_button ) );
                    btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
                } else {
                    changeBottomSave();
                    textView.setVisibility( View.INVISIBLE );
                }
            } else {
                changeBottomSave();
                textView.setVisibility( View.INVISIBLE );
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {


        }


    }

    class WatcherZW implements TextWatcher {
        EditText etTextView;
        TextView textView;

        WatcherZW(EditText odR1mm, TextView tvOdR1mm) {
            this.etTextView = odR1mm;
            this.textView = tvOdR1mm;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
//            etTextView.setFocusable( true );//设置输入框可聚集
//            etTextView.setFocusableInTouchMode( true );//设置触摸聚焦
//            etTextView.requestFocus();//请求焦点
//            etTextView.findFocus();//获取焦点
            String trim = etTextView.getText().toString().trim();

            // 新轴位正则表达式：整数，且在0~180之间，支持+000，+012，+002这样的格式

            String regZW = "^[+]?(0?0?\\d|0?\\d{2}|1[0-7]\\d|180)$";
            if (!UtilString.isEmpty( trim )) {
                if (!trim.matches( regZW )) {
                    textView.setVisibility( View.VISIBLE );
                    tvVision.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_grey_stroke_25 ) );
                    tvVision.setTextColor( ContextCompat.getColor( activity, R.color.ffd3dcdc ) );
                    btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_light_blue_button ) );
                    btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
                } else {
                    textView.setVisibility( View.INVISIBLE );
                    changeBottomSave();
                }

            } else {
                changeBottomSave();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    }

    void changeBottomSave() {
        if (!isEmptyRemark) {
            //备注不为空
            tvVision.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_stroke ) );
            tvVision.setTextColor( ContextCompat.getColor( activity, R.color.mainColor ) );
            btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_button ) );
            btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
        } else {
            if (TextUtils.isEmpty( odSph.getText().toString() ) || TextUtils.isEmpty( osSph.getText().toString() ) || TextUtils.isEmpty( odCyl.getText().toString() ) || TextUtils.isEmpty( osCyl.getText().toString() ) || TextUtils.isEmpty( odAxial.getText().toString() ) || TextUtils.isEmpty( osAxial.getText().toString() )) {
                tvVision.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_grey_stroke_25 ) );
                tvVision.setTextColor( ContextCompat.getColor( activity, R.color.ffd3dcdc ) );
                btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_light_blue_button ) );
                btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
            } else {
                tvVision.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_stroke ) );
                tvVision.setTextColor( ContextCompat.getColor( activity, R.color.mainColor ) );
                btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_button ) );
                btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
            }
        }
    }

    /**
     * 初始化球镜柱镜二级联动数据
     *
     * @time 2020/12/15 9:46
     */
    private void initList() {
        options1Items.addAll( DiopterDataUtil.initListItemsOne() );
        options2Items.addAll( DiopterDataUtil.initListItemsTwo() );
        options3Items.addAll( DiopterDataUtil.initListItemsThree() );
    }

    //回显球镜数据,判断范围
    private void showCurrentQiuJingData(String trim) {
        if (!TextUtils.isEmpty( trim )) {
            for (String dataOne : options1Items) {
                for (String dataTwo : options2Items) {
                    String listData = dataOne + dataTwo;
                    if (listData.equals( trim )) {
                        String[] temp = trim.split( "\\." );
                        LogUtil.e( "回显数据" + trim );
                        if (Integer.parseInt( temp[0] ) > 0) {
                            pvOptions_qiujing.setSelectOptions( Math.abs( Integer.parseInt( temp[0] ) ), Integer.parseInt( temp[1] ) / 25 );
                        } else {
                            pvOptions_qiujing.setSelectOptions( Math.abs( Integer.parseInt( temp[0] ) - 21 ), Integer.parseInt( temp[1] ) / 25 );
                        }
                    }
                }

            }

        } else {
            pvOptions_qiujing.setSelectOptions( 20, 0 );
        }
    }

    //回显柱镜数据,判断范围
    private void showCurrentZhuJingData(String trim) {
        if (!TextUtils.isEmpty( trim )) {
            for (String dataOne : options1Items) {
                for (String dataTwo : options2Items) {
                    String listData = dataOne + dataTwo;
                    if (listData.equals( trim )) {
                        String[] temp = trim.split( "\\." );
                        pvOptions_zhujing.setSelectOptions( Math.abs( Integer.parseInt( temp[0] ) ), Integer.parseInt( temp[1] ) / 25 );

                    }
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView( inflater, container, savedInstanceState );
        assert rootView != null;
        unbinder = ButterKnife.bind( this, rootView );
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
